package game.model
{
	import com.greensock.TweenLite;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.geom.Point;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import game.event.EventName;
	import game.event.GameEvent;
	import game.model.pathing.AStar;
	import game.model.pathing.Grid;
	import game.model.vo.SceneInfoVo;

	public class SceneModel extends EventDispatcher
	{
		private static var instance:SceneModel;	
		
		public var sceneInfoVo:SceneInfoVo;
		
		public var width:uint;
		public var length:uint;
		public var height:uint;
		public var gridSize:Number;
		/**地图xml数据*/
		public var xml:XML;
		
		private var _pathGrid:Grid;
		private var _astar:AStar;
		
		/**顾客方向数组*/
		public var cusDirArr:Array;
		/**服务员方向数组*/
		public var emDirArr:Array;
		public function SceneModel()
		{
			if (!instance) {
				instance = this;
				init();
			}else
				throw new Error("SceneModel is a single class");
		}
		
		public static function getInstance():SceneModel
		{
			if (!instance)
				instance = new SceneModel();
			return  instance;
		}
		
		private function init():void
		{
			//dispatchEvent(new Event(EventName.ENTER_SCENE));
			cusDirArr=[];
			emDirArr=[];
		}
		
		public function buildScene(value:SceneInfoVo):void
		{
			if (value == null) return;
			
			sceneInfoVo = value;
			
			width=sceneInfoVo.width;
			length=sceneInfoVo.length;
			height=sceneInfoVo.height;
			gridSize=sceneInfoVo.gridSize;
			
			xml=sceneInfoVo.xml;
			
			_astar=new AStar();
			/**8,11*/
			_pathGrid=new Grid(width,length);
			
			_pathGrid.setWalkable(2, 2, false);
			//_pathGrid.setWalkable(3, 2, false);
			_pathGrid.setWalkable(2, 4, false);
			//_pathGrid.setWalkable(3, 4, false);
			
			dispatchEvent(new GameEvent(EventName.INIT_SCENE));
		}
		
		
		/**
		 * 寻找路径
		 * @param startPoint
		 * @param endPoint
		 * @param occupy false-服务员,true-顾客
		 * @return
		 */
		public function findPath(startPoint:Point,endPoint:Point,occupy:Boolean):Array
		{				
			_pathGrid.setStartNode(startPoint.x,startPoint.y);
			_pathGrid.setEndNode(endPoint.x,endPoint.y);
			var res:Array=[];
			//dirArr=[];
			if (_astar.findPath(_pathGrid))
			{
				res=_astar.path;
				/**
				 * 无论深复制或浅复制都无法奏效,还不如直接建多个数组方便
				 * */
				if (occupy) 
				{
					cusDirArr = _astar.getDirection();
				}
				else
					emDirArr = _astar.getDirection();
			}
			return res;
		}
		
		public function dispose():void
		{
			emDirArr.splice(0);
			emDirArr=null;
			
			cusDirArr.splice(0);
			cusDirArr=null;		
		}

		/**寻路*/
		public function get pathGrid():Grid
		{
			return _pathGrid;
		}


	}
}